local redis_client = require "lib.redis"
local args = ngx.req.get_uri_args()

if nil == args.vote_id then
    ngx.say('{"code":10000,"message":"vote_id不能为空"}')
    return
end

local vote_id = args.vote_id
local redis = redis_client:new()


local raw, err = redis:get('vote:'..vote_id)

if nil == raw then
    ngx.say('{"code":10000,"message":"活动不存在", "error":"', err, '"}')
    return
end

-- 根据投票数查出id和对应的票数
local rank, err = redis:zrevrangebyscore('ranking:'..vote_id, '+inf', 0, 'WITHSCORES')

if err ~= nil then
    ngx.log(ngx.ERR, 'connect redis faild:', err)
    ngx.say('{"code":10000,"message":"服务器内部错误"}')
    return
end

local votes

if not rank then
    votes = '{}'
else
    local ids, scores = {}, {}

    -- 将id和票数分别组装，并将id组合成取item得key
    for i, value in ipairs(rank) do
        if i % 2 == 0 then
            --票数
            table.insert(scores, value)
        else
            --id
            table.insert(ids, value)
        end
    end

    votes = '{'
    for of, id in ipairs(ids) do
        votes = votes ..'"'..id..'":'..scores[of]..','
    end

    -- lua的字符串的第一个索引是1
    votes = string.sub(votes, 1, -2)..'}'
end

ngx.say('{"code":200,"message":"success","data":{"votes":', votes, ',"details":', raw, '}}')

